package com.yzzrjy.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.StringUtils;
import com.tencentyun.TLSSigAPIv2;
import com.yzzrjy.Dao.Impl.MemoryDaoRedis;
import com.yzzrjy.Dao.Impl.UserDaoMsql;
import com.yzzrjy.Dao.Interfaces.MemoryDao;
import com.yzzrjy.Dao.Interfaces.UserDao;
import com.yzzrjy.bean.*;
import com.yzzrjy.data.QiNiu;
import com.yzzrjy.data.TencentData;
import com.yzzrjy.util.MyDateUtil;
import com.yzzrjy.util.TokenUtils;
import com.yzzrjy.util.UIDGeneratorUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class UserService {
    public static int mAddLength = 156;
    public static int mDefaultStartId = 555555;
    //用户状态
    public final static byte USER_STATE_NEW_REGISTER = 0; //新注册
    public final static byte USER_STATE_Normal = 1; //注册昵称性别后
    public final static byte USER_STATE_LOGOFF = -1; //注销

    //默认头像
    public final static String HEAD_DEFAULT = "app/head_default.jpg";
    public final static String SIG_DEFAULT = "这个家伙很懒，什么都没留下";

    //初始金币
    public final static int COIN_DEFAULT = 50;
    public final static int COIN_DEFAULT_PHONE = 138;
    public final static int SHOW_PAGE_SIZE = 20;
    private UserDao userDao = new UserDaoMsql();
    private MemoryDao memoryDao = new MemoryDaoRedis();

    public void registerInfo(String uid, String nickname, String sex) throws SQLException {
        userDao.registerInfo(uid, nickname, sex, USER_STATE_Normal);
    }

    public JSONObject phoneLogin(String phone) throws SQLException {
//        String uuidToken = UUID.randomUUID().toString().replace("-", "");

        String retUid;
        String retToken;
        byte status;

        UserBaseBean baseBean = userDao.getUserBaseByPhone(phone);
        if(baseBean != null){
            retUid = baseBean.getUid();
            retToken = TokenUtils.getToken(retUid);
            status = baseBean.getStatus();
        }else{
            //注册到数据库
            long newId = UIDGeneratorUtils.getUID();
            userDao.addNewUserByPhone(newId, phone, USER_STATE_NEW_REGISTER, COIN_DEFAULT_PHONE, HEAD_DEFAULT, SIG_DEFAULT);
            retUid = String.valueOf(newId);
            retToken = TokenUtils.getToken(retUid);
            status = USER_STATE_NEW_REGISTER;
        }
        JSONObject jsonInfoObject = new JSONObject();
        jsonInfoObject.put("uid", retUid);
        jsonInfoObject.put("token", retToken);
        jsonInfoObject.put("status",status);

        TLSSigAPIv2 api = new TLSSigAPIv2(TencentData.TX_SDK_APPID, TencentData.TX_SECRET_KEY);
        String userSig = api.genUserSig(retUid, TencentData.TX_EXPIRE_TIME);
        jsonInfoObject.put("txusersig", userSig);
        return jsonInfoObject;
    }

    public boolean checkUserToken(String uid, String token) {
        if(uid == null || token == null){
            return false;
        }
        return TokenUtils.verifyToken(uid, token);
    }

    public UserBaseBean getUserBase(String uid) throws SQLException {
        UserBaseBean userBaseBean = userDao.getUserMe(uid);
        if(userBaseBean == null){
            return null;
        }
        String face = userBaseBean.getFace();
        if(face != null){
            userBaseBean.setFace(QiNiu.getOriginalFileUrl(face));
            userBaseBean.setSmall_face(QiNiu.getSmallImageUrl(face));
        }
        //获取vip时间
        if(getUserVipDays(uid) >= 0){
            userBaseBean.setIs_vip(true);
        }else {
            userBaseBean.setIs_vip(false);
        }
        return userBaseBean;
    }

    public int getUserVipDays(String uid) throws SQLException {
        UserVipBean vipBean = userDao.getUserVipBean(uid);
        return calcVipDays(vipBean);
    }

    private int calcVipDays(UserVipBean vipBean){
        if(vipBean == null){
            return -1;
        }
        int dayCount = vipBean.getDay_count();
        Date startTime = vipBean.getStart_time();
        int days = (int) ((System.currentTimeMillis() - startTime.getTime()) / (1000*3600*24));
        return dayCount - days;
    }

    public UserLiveBean getUserLiveBean(String liveUid, String myUid) throws SQLException{
        UserLiveBean userLiveBean = userDao.getUserLiveBean(liveUid, myUid);
        if(userLiveBean == null){
            return null;
        }
        String face = userLiveBean.getFace();
        String album = userLiveBean.getAlbum();
        String front_cover = userLiveBean.getFront_cover();
        String sound_record = userLiveBean.getSound_record();
        String birthday = userLiveBean.getBirthday();
        //face
        if(face != null){
            userLiveBean.setFace(QiNiu.getOriginalFileUrl(face));
            userLiveBean.setSmall_face(QiNiu.getSmallImageUrl(face));
        }
        //datum
        if(album != null){
            userLiveBean.setAlbum_list(ServiceUtils.originJsonToAlbumList(album));
        }
        if(front_cover != null){
            userLiveBean.setFront_cover(QiNiu.getOriginalFileUrl(front_cover));
        }
        if(sound_record != null){
            userLiveBean.setSound_record(QiNiu.getOriginalFileUrl(sound_record));
        }
        //age
        if(birthday != null){
            int age = MyDateUtil.getAgeFromBirthday(birthday);
            if(age > 0){
                userLiveBean.setAge(String.valueOf(age));
            }
        }
        //vip
        if(getUserVipDays(liveUid) >= 0){
            userLiveBean.setIs_vip(true);
        }else {
            userLiveBean.setIs_vip(false);
        }
        return userLiveBean;
    }

    public EditInfoBean getEditInfo(String uid) throws SQLException {
        EditInfoBean editInfo = userDao.getEditInfo(uid);
        if(editInfo == null){
            return null;
        }
        String face = editInfo.getFace();
        String album = editInfo.getAlbum();
        String front_cover = editInfo.getFront_cover();
        String sound_record = editInfo.getSound_record();
        if(face != null){
            editInfo.setFace(QiNiu.getOriginalFileUrl(face));
            editInfo.setSmall_face(QiNiu.getSmallImageUrl(face));
        }
        if(album != null){
            editInfo.setAlbum_list(ServiceUtils.originJsonToAlbumList(album));
        }
        if(front_cover != null){
            editInfo.setFront_cover(QiNiu.getOriginalFileUrl(front_cover));
        }
        if(sound_record != null){
            editInfo.setSound_record(QiNiu.getOriginalFileUrl(sound_record));
        }
        return editInfo;
    }

    public List<UserShowBean> getOnlineUserList(String myUid, String sex, int page) throws SQLException{
        int start = (page - 1) * SHOW_PAGE_SIZE;
        List<UserShowBean> list = userDao.getOnlineUserList(myUid, sex, start, SHOW_PAGE_SIZE);
        fillUserShowBeanList(list);
        return list;
    }

    public List<UserShowBean> getOnlineUserListByMemory(String myUid, String sex, int page) throws SQLException {
        int start = (page - 1) * SHOW_PAGE_SIZE;
        List<String> uidList = memoryDao.getOnlineUsers(sex, start, SHOW_PAGE_SIZE);
        if(uidList == null || uidList.size() == 0){
            return null;
        }
        String uidS = StringUtils.join(uidList, ",");
        List<UserShowBean> beanList = userDao.getOnlineUserList(myUid, uidS);
        fillUserShowBeanList(beanList);
        return beanList;
    }

    private void fillUserShowBeanList(List<UserShowBean> list){
        if(list != null && list.size() > 0){
            //随机排序
            Collections.shuffle(list);
            //计算face age
            for (UserShowBean bean : list) {
                String face = bean.getFace();
                String birthday = bean.getBirthday();
                if(face != null){
                    bean.setFace(QiNiu.getOriginalFileUrl(face));
                    bean.setSmall_face(QiNiu.getSmallImageUrl(face));
                }
                if(birthday != null){
                    int age = MyDateUtil.getAgeFromBirthday(birthday);
                    if(age > 0){
                        bean.setAge(String.valueOf(age));
                    }
                }
            }

        }
    }

    public List<String> updateAlbum(String uid, String remoteAlbums) throws SQLException {
        List<String> upList = JSON.parseArray(remoteAlbums, String.class);
        if(upList == null || upList.size() == 0){
            return null;
        }
        UserLiveBean liveBean = userDao.getUserInfoTable(uid);
        if(liveBean == null){
            throw new RuntimeException("用户不存在");
        }

        do {
            String dbAlbum = liveBean.getAlbum();
            if(dbAlbum == null){
                userDao.updateAlbum(uid, remoteAlbums);
                break;
            }
            List<String> dbList = JSON.parseArray(dbAlbum, String.class);
            if(dbList == null || dbList.size() == 0){
                userDao.updateAlbum(uid, remoteAlbums);
                break;
            }
            dbList.addAll(upList);
            String upJson = JSON.toJSONString(dbList);
            userDao.updateAlbum(uid, upJson);
        }while (false);

        List<String> retList = new ArrayList<>();
        for (String s : upList) {
            retList.add(QiNiu.getOriginalFileUrl(s));
        }
        return retList;
    }

    public boolean deleteAlbum(String uid, String url) throws SQLException {
        UserLiveBean liveBean = userDao.getUserInfoTable(uid);
        if(liveBean == null){
            return false;
        }
        String dbAlbum = liveBean.getAlbum();
        if(dbAlbum == null){
            return false;
        }
        List<String> dbList = JSON.parseArray(dbAlbum, String.class);
        if(dbList == null || dbList.size() == 0){
            return false;
        }
        boolean deleted = false;
        for (int i = 0; i < dbList.size(); i++) {
            if(url.contains(dbList.get(i))){
                dbList.remove(i);
                deleted = true;
                break;
            }
        }
        if(deleted){
            String album = JSON.toJSONString(dbList);
            userDao.updateAlbum(uid, album);
            return true;
        }
        return false;
    }

    public String updateFace(String uid, String remoteName) throws SQLException {
        userDao.updateFace(uid, remoteName);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("original", QiNiu.getOriginalFileUrl(remoteName));
        jsonObject.put("small", QiNiu.getSmallImageUrl(remoteName));
        return jsonObject.toJSONString();
    }


    public int updateUserInfo(String uid, JSONObject jsonObject) throws SQLException {
        if(uid == null || jsonObject == null || jsonObject.size() == 0){
            return 0;
        }
        String nickname = jsonObject.getString("nickname");
        if(nickname != null && searchNickname(uid, nickname)){
            return -1;
        }
        userDao.updateUserInfo(uid, jsonObject);
        return 1;
    }

    private boolean searchNickname(String uid, String nickname) throws SQLException {
        int count = userDao.searchNickname(nickname);
        if(count > 0){
            return true;
        }
        return false;
    }

    private void updateBirthday(String uid, String birthday, boolean cardAttest) throws SQLException {
        userDao.updateBirthday(uid, birthday, cardAttest);
    }

    public List<UserLetBean> getUserLetList(String uidS) throws SQLException {
        List<UserLetBean> userLetList = userDao.getUserLetList(uidS);
        //设置头像
        for (UserLetBean userLetBean : userLetList) {
            String face = userLetBean.getFace();
            if(face != null){
                userLetBean.setFace(QiNiu.getOriginalFileUrl(face));
                userLetBean.setSmall_face(QiNiu.getSmallImageUrl(face));
            }
        }
        //设置vip
        List<UserVipBean> vipBeanList = userDao.getUserVipList(uidS);
        if(vipBeanList != null && vipBeanList.size() > 0){
            for (UserVipBean vipBean : vipBeanList) {
                for (UserLetBean userLetBean : userLetList) {
                    if(vipBean.getUid().equals(userLetBean.getUid())){
                        if(calcVipDays(vipBean) >= 0){
                            userLetBean.setIs_vip(true);
                        }else {
                            userLetBean.setIs_vip(false);
                        }
                        break;
                    }
                }
            }
        }
        return userLetList;
    }
}
